package com.bath.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bath.Constants;
import com.bath.util.StringUtil;


public class LoginFilter implements Filter {
	
	protected FilterConfig filterConfig;
	private static final String[] DEFAULT_INCLUDE_KEYS = { "edit","update", "admin", "input", "create", "remove","delete","home", };
	private static final String[] DEFAULT_EXCLUDE_SUFFIXS = { ".js", ".css", ".jpg", ".gif", ".png" };
	
	public void doFilter(final ServletRequest req, final ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) req;
		HttpServletResponse hres = (HttpServletResponse) res;
		String isLog = "false";
		
		if(notFilter(hreq)) {
			chain.doFilter(req, res);
			return;
		}else if(shouldFilter(hreq)) isLog = (String)hreq.getSession().getAttribute(Constants.IS_LOGIN);
		else {
			chain.doFilter(req, res);
			return;
		}
		if (StringUtil.notEmpty(isLog) && ((isLog.equals("true")) || (isLog == "true")))
		{
			if(hreq.getRequestURI().indexOf(Constants.LOGIN_URL) == -1) {
				chain.doFilter(req, res);
				return;
			}
			else hres.sendRedirect(hreq.getContextPath() + Constants.PAGE_MAIN);
		}
		else if(hreq.getRequestURI().indexOf(Constants.LOGIN_URL) > 0) {
			chain.doFilter(req, res);
			return;
		}
		else {
			String originalURL = hreq.getServletPath()
			+ (hreq.getPathInfo() == null ? "" : hreq.getPathInfo())
			+ (hreq.getQueryString() == null ? "" : "?"
			+ hreq.getQueryString());
			
			hres.sendRedirect(hreq.getContextPath() + Constants.LOGIN_URL+"?destUrl="+originalURL);
		}
	}

	public void destroy() {
		this.filterConfig = null;
	}
	
	public void init(FilterConfig config) {
		this.filterConfig = config;
	}
	
	public void setFilterConfig(final FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}
	
	protected boolean notFilter(final HttpServletRequest request) throws ServletException {
		String url = request.getRequestURI();
		boolean result = false;
		
		for (String suffix : DEFAULT_EXCLUDE_SUFFIXS) {
			result = url.endsWith(suffix);
			if(result) break;
		}	
		return result;
	}
	
	protected boolean shouldFilter(final HttpServletRequest request) throws ServletException {
		String url = request.getRequestURI() + (request.getQueryString() == null ? "" : ("?" + request.getQueryString()));
		boolean result = false;
				
		for (String suffix : DEFAULT_INCLUDE_KEYS) {
			result = url.contains(suffix);
			if(result) break;
		}
		return result;
	}

}
